package servlet;

import bean.Advice;
import dao.AdminDao;
import dao.AdviceDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@WebServlet(name="manager_login",urlPatterns = "/manager_login")
public class manager_login extends HttpServlet{
    @Override
    protected  void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String name=req.getParameter("log");

        String password=req.getParameter("pwd");
        String rememberme=req.getParameter("rememberme");

        AdminDao dao = new AdminDao();
        String type = null;
        try {
            type=String.valueOf(dao.check(name,password));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(type.equals("-1")) {
            req.setAttribute("msg","用户名或密码错误");
            req.getRequestDispatcher("/adm/managerLogin.jsp").forward(req,resp);
        }
        if(rememberme!=null&&rememberme.equals("forever")){
            //把用户名和密码保存在Cookie对象里面
            String username = URLEncoder.encode(name,"utf-8");
            //使用URLEncoder解决无法在Cookie当中保存中文字符串问题
            String typeStr = URLEncoder.encode(type,"utf-8");

            Cookie usernameCookie = new Cookie("username",username);
            usernameCookie.setPath("/");
            Cookie passwordCookie = new Cookie("type",typeStr);
            passwordCookie.setPath("/");
            usernameCookie.setMaxAge(864000);
            passwordCookie.setMaxAge(864000);//设置最大生存期限为10天
            resp.addCookie(usernameCookie);
            resp.addCookie(passwordCookie);
        }
        req.getSession().setAttribute("name",name);
        req.getSession().setAttribute("type",type);
        if(type.equals("0")) {
            resp.sendRedirect("/adm/superManager.jsp");
        }else if(type.equals("1")){
            resp.sendRedirect("/adm/mailBoxManager.jsp");
        }else if(type.equals("2")){
            resp.sendRedirect("/adm/cafManager.jsp");
        }

    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}